package com.kaifamiao.lock;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class LockTest {

    public static void main(String[] args) throws InterruptedException {
        String name = Thread.currentThread().getName();
        System.out.printf("%s线程开始\n", name);

        final Lock lock = new ReentrantLock();

        Thread t = new Thread( () -> {
            String threadName = Thread.currentThread().getName();
            System.out.printf("%s线程开始\n", threadName);
            lock.lock(); // 获得锁
            try {
                System.out.printf("%s线程即将释放同步锁\n", threadName);
                lock.unlock(); // 释放锁
                Thread.sleep( 500L );
                lock.lock(); // 获得锁
                System.out.printf("%s线程恢复运行\n", threadName);
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                lock.unlock(); // 释放锁
            }
            System.out.printf("%s线程结束\n", threadName);
        }, "孙悟空");

        t.start();

        Thread.sleep( 500L );

        lock.lock();
        System.out.printf("我是%s\n", name);
        lock.unlock();

        System.out.printf("%s线程结束\n", name);
    }

}
